package cn.wuyi.common.rest;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

public class RestTemplateHolder {
	
	private static Logger logger  = LoggerFactory.getLogger(RestTemplateHolder.class);
	
	//默认连接超时时间
	private static int DEFAULT_CONNECTTIMEOUT = 1000 * 30;
		
	//默认读取超时时间
	private static int DEFAULT_READTIMEOUT = 1000 * 30;
		
	private static ThreadLocal<RestTemplateExt> local = new ThreadLocal<RestTemplateExt>();
	
	public static RestTemplateExt getRestTemplate(){
		RestTemplateExt restTemplate = local.get();
		if(restTemplate == null){
			HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
			requestFactory.setConnectTimeout(DEFAULT_CONNECTTIMEOUT);
			requestFactory.setReadTimeout(DEFAULT_READTIMEOUT);
			logger.debug("初始化RestTemplate的超时时间connectTimeout=" + DEFAULT_READTIMEOUT + ";readTimeout=" + DEFAULT_READTIMEOUT);
			restTemplate = new RestTemplateExt(requestFactory);
			local.set(restTemplate);
		}
		return restTemplate;
	}
	
	public static RestTemplateExt getTemplateByActionUrl(String actionUrl){
		RestTemplateExt template = getRestTemplate();
		logger.debug("### RestTemplateExt: tenatId is -> {}, appId is -> {}",template.getTenantId(),template.getAppId());
		return template;
	}
	
	public static void setTemplate(RestTemplateExt restTemplateExt){
		local.set(restTemplateExt);
	}
	
	public void cleanTemplate(){
		local.set(null);
	}
	
	/**
	 * @方法功能说明：清理从当前线程中获取的RestTemplateExtd对象的属性,使其恢复默认值,防止影响其他方法调用
	 * 原因：每次从当前线程获取RestTemplateExtd发送http请求结束后,并不需要清理当前线程的RestTemplateExtd对象,但需要清理该RestTemplateExtd对象的属性
	 * @作者        : administrator
	 * @创建时间    ：2018年7月16日 下午5:38:52
	 */
	public static void cleanTemplateAttr(){
		RestTemplateExt restTemplateExt = local.get();
		restTemplateExt.clearAttr();
		local.set(restTemplateExt);
	}

}
